<template>
    <div class="mainContentDiv">
        <div class="formContent">
            <div class="title">
                <span>个人信息</span>
            </div>
            <div class="listDown baseInfo">
                <el-form action="" :model="form" ref="form">
                    <el-form-item label="" prop="userName" class="worksItem userInput" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>用户名称</span></div> 
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.userName" class="elInputCom" :disabled="!edit"></el-input>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="" prop="sex" class="worksItem userInput" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>性别</span> </div>
                            <div class="inputStyle">
                                <el-select class="elInput userInfoSelect" v-model="form.sex" placeholder="请选择">
                                    <el-option
                                    v-for="item in sexOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </el-form-item>
                    
                    <el-form-item label="" prop="phone" class="worksItem userInput" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>手机号</span> </div>
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.phone" class="elInputCom" :disabled="edit"></el-input>
                                <!-- <i class="el-icon-edit-outline" title="修改手机号"></i> -->
                            </div>
                            
                        </div>
                    </el-form-item>
                    <el-form-item label="" prop="email" class="worksItem userInput">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>邮箱</span> </div>
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.email" class="elInputCom" :disabled="edit"></el-input>
                                <!-- <i class="el-icon-edit-outline" title="修改邮箱"></i> -->
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="" prop="phone" class="worksItem userInput" >
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>QQ</span> </div>
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.qq" class="elInputCom" :disabled="edit"></el-input>
                                <!-- <i class="el-icon-edit-outline" title="修改QQ"></i> -->
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="" prop="email" class="worksItem userInput" >
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>微信</span> </div>
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.weiChat" class="elInputCom" :disabled="edit"></el-input>
                                <!-- <i class="el-icon-edit-outline" title="修改微信"></i> -->
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="" prop="orgId" class="worksItem userInput">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>所属单位</span> </div>
                            <div class="inputStyle">
                                <select-tree v-model="form.orgId" :multiple="true" placeholder="请选择" :options="unitOptions" class="userInfoSelect" :disabled="edit"/>
                            </div>
                            
                        </div>
                    </el-form-item>
                    <el-form-item label="" prop="roleId" class="worksItem userInput" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>角色</span> </div>
                            <div class="inputStyle">
                                <el-input type="text" name="worksName" v-model="form.roleName" class="elInputCom" :disabled="edit"></el-input>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="" prop="roleId" class="worksItem" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                        <div class="worksInput">
                            <div class="labelText"><i></i><span>其他</span> </div>
                            <div class="inputStyle change">
                                <span @click="updatePwd">修改密码</span>
                                <span @click="changeRole">变更角色</span>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            
        </div>

        <div slot="footer" class="dialog-footer">
            <el-button class="elBtn" type="primary" @click="backToIndex">返 回</el-button>
            <el-button class="elBtn" type="primary" @click="updateInfo">确 定</el-button>
        </div>
        <!-- 修改密码对话框 -->
        <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="30%" center>
            <el-form :model="psdForm" ref="psdForm" :rules="rules" label-width="20%" class="demo-ruleForm">
                <el-form-item label="原始密码"  prop="password">
                    <el-input class="elInput" type="password" v-model="psdForm.password" ></el-input>
                </el-form-item>
                
                <el-form-item label="新密码"  prop="pass">
                    <el-input class="elInput" type="password" v-model="psdForm.pass" ></el-input>
                </el-form-item>
                <el-form-item label="重复密码"  prop="newPassword">
                    <el-input class="elInput" type="password" v-model="psdForm.newPassword" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="cancelPsdDialog">取 消</el-button>
                <el-button class="elBtn" type="primary" @click.native="savePwd">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 角色变更对话框 -->
        <el-dialog title="修改角色" :visible.sync="changeRoleVisible" width="30%" center @close="cancelRoleDialog">
            <el-form :model="changeRoleform" ref="changeRoleform" label-width="20%" class="demo-ruleForm">
                <el-form-item label="用户名"  prop="">
                    <el-input class="elInput" type="text" v-model="changeRoleform.userName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="当前角色"  prop="">
                    <el-input class="elInput" type="text" v-model="changeRoleform.currRole" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="变更为"  prop="roleId" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                    <el-select class="elInput" v-model="changeRoleform.roleId" placeholder="请选择">
                        <el-option
                        v-for="item in roleOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="cancelRoleDialog">取 消</el-button>
                <el-button class="elBtn" type="primary" @click.native="saveRoleChange">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
    data(){
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入新密码'));
            } else if(value === this.psdForm.password){
                callback(new Error('新旧密码不能相同'));
            }
             else {
                if (this.form.newPassword !== '') {
                    this.$refs.form.validateField('newPassword');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入新密码'));
            } else if (value !== this.psdForm.pass) {
                callback(new Error('两次输入密码不一致!'));
            } 
            else {
                callback();
            }
        };
        var validatePass3 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入原密码'));
            }
             else {
                callback();
            }
        };
        return {
            dialogFormVisible:false,
            changeRoleVisible:false,
            edit:true,
            sexOptions:[ 
                {label:"男",value:2},
                {label:"女",value:1}
            ],
            psdForm:{ // 用户修改密码的表单数据
                phone:"",
                password:"",
                pass:"",
                newPassword:""
            },
            rules: { // 用户修改密码的验证规则
                password: [
                    { validator: validatePass3, trigger: ['blur', 'change'] },
                ],
                pass: [
                    { validator: validatePass, trigger: ['blur', 'change'] }
                ],
                newPassword: [
                    { validator: validatePass2, trigger: ['blur', 'change'] }
                ],
            },
            changeRoleform:{
                userId:"",
                userName:"",
                currRole:"",
                oldRoleId:"",
                roleId:""
            },
            roleOptions:[], // 角色数据
            roleOptions2:[], // 角色数据
            unitOptions:[], // 单位数据
            form: { // 表单参数
                userName: '',
                sex: '',
                phone: '',
                email: '',
                roleId: [],
                orgId:["01"],
                status:"",
                qq:"",
                weiChat:"",
                roleName:""
            },
            userInfo:""
        }
    },
    created(){
        this.selectById()
        // 获取角色数据
        this.$common.getAllRoles(res => {

            // 处理角色数据，角色变更时不能选择用户当前角色及管理员
            res.data.data.forEach((element,index) => {
                // if(element.name == "")
                if(element.name == "管理员"){
                    res.data.data.splice(index,1)
                }
                if(this.form.roleName.indexOf("管理员") == -1){
                    if(element.id == this.form.roleId[0]){
                        res.data.data.splice(index,1)
                    }
                }
                
            })
            this.roleOptions = res.data.data
        })

        // 获取单位数据
        this.$common.selectAllUnit(res => {
            this.unitOptions = this.$common.dataFormat(res.data.data)
        })

        
    },
    methods:{
        // 修改密码
        updatePwd(){
            this.form.phone = this.userInfo.phone
            this.dialogFormVisible = true
        },
        // 根据用户id查看用户信息
        selectById(){
            this.userInfo = localStorage.userInfo?JSON.parse(localStorage.userInfo):""
            this.$api.selectUserById({params:{id: this.userInfo.id}})
            .then(result=>{
                if(result.data.success){
                    if(result.data.data.roles && result.data.data){
                        result.data.data.roleName = []
                        result.data.data.roleId = []
                        result.data.data.orgId = []
                        
                        result.data.data.roles.forEach(element => {
                            result.data.data.roleName.push(element.name)
                            result.data.data.roleId.push(element.id)
                        })
                        result.data.data.organizations.forEach(element => {
                            result.data.data.orgId.push(element.id)
                        })
                    }
                    this.form = result.data.data
                    this.form.roleName = result.data.data.roleName.join(",")

                    this.changeRoleform.userId = result.data.data.id 
                    this.changeRoleform.userName = result.data.data.userName
                    this.changeRoleform.currRole = result.data.data.roleName
                    this.changeRoleform.oldRoleId = result.data.data.roleId[0]

                    this.psdForm.phone = result.data.data.phone
                }
            })
        },
        updateInfo(){
            this.$refs['form'].validate((valid) => {
                if(valid){
                    this.form.createTime = ""
                    this.form.roles = []
                    this.$api.modifyUser(this.form)
                    .then(result=>{
                        this.$common.getUserInfoById(this.form.id)
                        this.successFun(result)
                    })
                }
            })
        },
        backToIndex(){
            this.$router.push({
                path: '/backIndex'
            })
        },
        // 保存密码
        savePwd(){
            // 提交时验证
            this.$refs['psdForm'].validate((valid) => {
                if(valid){
                    this.$api.modifyPwd(this.psdForm)
                    .then(result => {
                        var _this = this
                        this.$common.filterLogin(result,_this,()=>{
                            if(result.data.success){
                                // 关闭对话框并清空表单 并重新登陆
                                _this.cancelPsdDialog()
                                // 清楚token
                                localStorage.removeItem('token');
                                // Toast("密码修改成功，请重新登陆")
                                this.$message({center: true,message: "密码修改成功，需要重新登陆",type: 'warning'});
                                // 跳转到登陆页
                                _this.$router.push('/login')
                            }else{
                                _this.$refs.psdForm.fields.filter((item) => (item.prop === 'password'))[0].validateMessage = result.data.message
                                _this.$refs['psdForm'].fields[0].validateState = 'error'
                            }
                        })
                    })
                }
            })
            
        },
        
        // 接口调用成功的方法
        successFun(result){
            var _this = this
            this.$common.filterLogin(result,_this,()=>{
                // _this.clearForm()
                _this.form.roleId = []
                if(result.data.success){
                    _this.$message({center: true,message: result.data.message?result.data.message:"操作成功",type: 'success'});
                }
                _this.selectById()
                // this.$router.push('/backIndex')
            })
            
        },
        // 修改用户角色
        changeRole(){
            this.changeRoleVisible = true
            this.userInfo.oldRoleId = this.userInfo.roleId
        },
        // 保存变更
        saveRoleChange(){
            this.$refs["changeRoleform"].validate(valid=> {
                if(valid){
                    this.$api.insertAudit(this.changeRoleform).then(result => {
                        var _this = this
                        this.$common.filterLogin(result,_this,()=>{
                            _this.changeRoleVisible = false
                            _this.roleId = ""
                        if(result.data.success){
                                this.$message({center: true,message: result.data.message,type: 'success'});
                            }else{
                                this.$message({center: true,message: result.data.message,type: 'warning'});
                            }
                        })
                    })
                }
            })
        },
        
        // 关闭密码对话框
        cancelPsdDialog(){
            this.dialogFormVisible = false
            // 清楚表单数据
            for(let item in this.psdForm){
                this.psdForm[item] = ""
            }
            this.$refs['psdForm'].clearValidate()?this.$refs['psdForm'].clearValidate():""
        },
        // 关闭角色对话框
        cancelRoleDialog(){
            this.changeRoleVisible = false
            // // 清楚表单数据
            // for(let item in this.changeRoleform){
            //     this.changeRoleform[item] = ""
            // }
            this.changeRoleform.roleId = ""
            this.$refs['changeRoleform'].clearValidate()?this.$refs['changeRoleform'].clearValidate():""
        },
    },
    components: {
      'select-tree': Treeselect
    }
}
</script>

<style lang="scss" scoped>
.mainContentDiv{
    width:70%;
    height:98%;
    text-align: center;
    margin:auto;
    margin-top:30px;
    .formContent{
        height: 86%;
        background: #fff;
        border: 2px solid #76383B;
        border-radius: 15px;
        .listDown{
            height: 86%;
            overflow-y: auto;
        }
    }
    .title{
        font-size: 18px;
        line-height:60px;
    }
    .el-form{
        display: flex;
        flex-wrap: wrap;
        justify-content:center;
        .el-form-item{
            width: 80%;
            margin-bottom:19px;
            .worksInput{
                display: flex;
                align-items: center;
                justify-content: space-between;
                .labelText{
                    display: flex;
                    align-items: center;
                    text-align: left;
                    >i{
                        display: inline-block;
                        width:20px;
                        height: 20px;
                        margin-right: 10px;
                        background: url('../../images/icon4.png') no-repeat;
                        background-size: 100% 100%;
                    }
                }
                .inputStyle{
                    text-align:left;
                    width: 75%;
                    >i{
                        // font-size: 16px;
                        color: #76383B;
                        cursor: pointer;
                    }
                    
                }
                .change span{
                    text-decoration: underline;
                    color: #D18C91;
                    cursor: pointer;
                }
                .inputStyle .el-input,.inputStyle .vue-treeselect,.inputStyle .el-select{
                    width: 95%;
                }
            }
        }
    }
    .dialog-footer{
        margin-top: 10px;
    }
}
</style>